<template>
  <div class="cg-checkbox">
    <label v-for="option in options" :key="option.id" class="cg-checkbox-item">
      <span class="cg-checkbox__input">
        <input v-model="selected" :value="option.id" class="cg-checkbox__original" type="checkbox"
          @change="handleSelect" />
      </span>
      <span class="cg-checkbox__label">{{ option.name }}</span>
    </label>
  </div>
</template>

<script setup lang="ts">
import {  ref, watch, onMounted } from 'vue'

defineOptions({
  name: 'cg-checkbox'
})

interface option {
  id: string | number
  name: string
}
interface Props {
  modelValue: any[]
  options: Array<option>
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  options: () => []
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: any[]): void
}>()

const selected = ref<any[]>([])

const updateValue = () => {
  selected.value = props.modelValue
}

const handleSelect = () => {
  emit('update:modelValue', selected.value)
}

watch(
  () => props.modelValue,
  () => {
    updateValue()
  }
)

onMounted(() => {
  updateValue()
})
</script>

<style lang="scss">
.cg-checkbox {
  .cg-checkbox-item {
    display: inline-block;
    white-space: nowrap;
    user-select: none;
    cursor: pointer;
    margin: 0 2rem 1rem 0;
    width: 6.25rem;
    line-height: 2rem;
    padding-left: 0.25rem;

    .cg-checkbox__label {
      white-space: normal;
      padding-left: 0.25rem;
    }

    .cg-checkbox__original {
      vertical-align: middle;
    }
  }
}
</style>
